<?php

/**
 * 
 * APP支付实现类
 * @author Josen
 *
 */
class AppPay {
    /* 生成APP提交数据 */

    public function GetAppParameters($UnifiedOrderResult, $KEY) {
        if (!array_key_exists("appid", $UnifiedOrderResult) || !array_key_exists("prepay_id", $UnifiedOrderResult) || $UnifiedOrderResult['prepay_id'] == "") {
            throw new WxPayException("参数错误");
        }
        $data['appid'] = $UnifiedOrderResult['appid'];
        $data['partnerid'] = $UnifiedOrderResult['mch_id'];
        $data['prepayid'] = $UnifiedOrderResult['prepay_id'];
        $data['package'] = 'Sign=WXPay';
        $data['noncestr'] = WxPayApi::getNonceStr();
        $data['timestamp'] = time();
        $data['sign'] = $this->MakeSign($data, $KEY);
        return $data;
    }

    /**
     * 生成签名
     *  @return 签名
     */
    public function MakeSign($params, $KEY) {
        //签名步骤一：按字典序排序数组参数
        ksort($params);
        $string = $this->ToUrlParams($params);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=" . $KEY;
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }

    /**
     * 将参数拼接为url: key=value&key=value
     * @param   $params
     * @return  string
     */
    public function ToUrlParams($params) {
        $string = '';
        if (!empty($params)) {
            $array = array();
            foreach ($params as $key => $value) {
                $array[] = $key . '=' . $value;
            }
            $string = implode("&", $array);
        }
        return $string;
    }

}
